import React, {useEffect, useState} from 'react';
import Swiper from "./components/Swiper";
import AreaTitle from "./components/AreaTitle";
import PlayList from "./components/PlayList";
import SwiperItem from "./components/SwiperItem";
import PlayItem from "./components/PlayItem";
import {Pagination} from "antd";
import styles from "./style.less";
import axios from "axios";

const Home = () => {
    const [bannerList, setBannerList] = useState([]);
    const [playList, setPlayList] = useState([]);
    const [current, setCurrent] = useState(1);

    const paginationOptions = {
        current: current,
        total: playList.length,
        onChange: (page, pageSize) => {
            setCurrent(page);
        }
    }

    const requestBanner = () => {
        axios.get('http://123.207.32.32:9001/banner').then(res => {
            if (res.data && res.data.banners) {
                setBannerList(res.data.banners);
            }
        }).catch(error => console.error(error));
    }

    const requestPlayList = () => {
        axios.get('http://123.207.32.32:9001/personalized').then(res => {
            if (res.data && res.data.result) {
                setPlayList(res.data.result);
            }
        }).catch(error => console.error(error));
    }

    const renderBanner = (dataList) => {
        if (Array.isArray(dataList)) {
            return dataList.filter(item => {
                // targetType 1 为单曲，targetType 为 专辑
                return item.targetType === 1 || item.targetType === 10;
            }).map(item => {
                const {imageUrl, targetId, targetType} = item;
                return (<SwiperItem id={targetId} cover={imageUrl} type={targetType} key={targetId}/>);
            });
        }

        return [];
    }

    const renderPlayList = (dataList) => {
        if (Array.isArray(dataList)) {
            return dataList.slice(10 * (current - 1), 10 * current).map(item => {
                const {picUrl, name, id} = item;
                return (<PlayItem title={name} cover={picUrl} url={"/singlelist/" + id} key={id}/>);
            });
        }

        return [];
    }

    useEffect(() => {
        requestBanner();
        requestPlayList();
    }, []);

    return (
        <div className={styles.homeContent}>
            <Swiper>
                {renderBanner(bannerList)}
            </Swiper>
            <div className={styles.playList}>
                <AreaTitle title={'热门推荐'} to={'/playlists'}/>
                <PlayList>
                    {renderPlayList(playList)}
                </PlayList>
                <Pagination className={styles.pagination}  {...paginationOptions} />
            </div>
        </div>
    );
}

export default Home;
